package se.rende.myrss;

import java.util.ArrayList;
import java.util.List;

import se.rende.myrss.data.ChannelUtil;
import se.rende.myrss.data.ChannelUtil.ChannelInfo;
import se.rende.myrss.data.Constants;
import se.rende.myrss.data.MyRSSDataHelper;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.CursorLoader;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.ViewGroup;

public class ItemDetailSwipeActivity extends FragmentActivity implements
LoaderCallbacks<Cursor> {
	private static final int ITEM_ID_LIST_LOADER = 0;
	private MyRSSDataHelper dataHelper;
	private List<String> itemIdList = new ArrayList<String>();
	private ViewPager pager;
	private String itemId;
	private boolean currentItemIsSet = false;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_item_detail_pager);
		pager = (ViewPager) findViewById(R.id.pager);
		dataHelper = new MyRSSDataHelper(this);
        Bundle arguments = new Bundle();
        itemId = getIntent().getStringExtra(ItemDetailFragment.ARG_ITEM_ID);
		arguments.putString(ItemDetailFragment.ARG_ITEM_ID, itemId);
        arguments.putString(ItemDetailFragment.ARG_CHANNEL_ID,
                getIntent().getStringExtra(ItemDetailFragment.ARG_CHANNEL_ID));

		getLoaderManager().initLoader(ITEM_ID_LIST_LOADER, arguments, this);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.item_detail, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
        case R.id.unseen:
        	unseen();
			return true;
        default:
            return super.onOptionsItemSelected(item);
		}
	}

	public void unseen() {
		setSeenStatus(itemIdList.get(pager.getCurrentItem()), false);
	}

	private void setSeenStatus(String itemId, boolean seen) {
		SQLiteDatabase database = dataHelper.getWritableDatabase();
		database.execSQL("update item set seen=? where _id=?", new Object[] {
				Long.valueOf(seen ? 1L : 0L), itemId });
		database.close();
	}

	private void initPager() {
		ItemPagerAdapter pagerAdapter = new ItemPagerAdapter(getSupportFragmentManager());
		pager.setAdapter(pagerAdapter);
		
		int i = itemIdList.indexOf(itemId);
		if (i == -1) {
			i = 0;
		}
		currentItemIsSet = true;
		pager.setCurrentItem(i);
	}
	
	class ItemPagerAdapter extends FragmentStatePagerAdapter {
		public ItemPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public int getCount() {
			return itemIdList.size();
		}
		
		@Override
		public void setPrimaryItem(ViewGroup container, int position,
				Object object) {
			super.setPrimaryItem(container, position, object);
			Log.d("ItemDetailSwipeActivity", "setPrimaryItem(" + container + ", " + position + ", " + object + ")");
			if (currentItemIsSet) {
				setSeenStatus(itemIdList.get(position), true);
			}
		}

		@Override
		public Fragment getItem(int i) {
            Bundle arguments = new Bundle();
            arguments.putString(ItemDetailFragment.ARG_ITEM_ID,
                    itemIdList.get(i));
            arguments.putString(ItemDetailFragment.ARG_CHANNEL_ID,
                    getIntent().getStringExtra(ItemDetailFragment.ARG_CHANNEL_ID));
            ItemDetailFragment fragment = new ItemDetailFragment();
            fragment.setArguments(arguments);
			return fragment;
		}
		
		
	}
	
	@Override
	public android.content.Loader<Cursor> onCreateLoader(int id, Bundle args) {
		String channelId = args.getString(ItemDetailFragment.ARG_CHANNEL_ID);
		Boolean showNew = args.getBoolean(ItemDetailFragment.ARG_SHOW_NEW_ID);
		ChannelInfo channelInfo = ChannelUtil.getChannelInfo(dataHelper,
				channelId);
		String[] projection = { "_id" };
		String cond = ChannelUtil.addCond(showNew ? "seen=0" : "", channelInfo.getChannelIdCond());
		return new CursorLoader(this, Constants.CONTENT_URI_ITEM,
				projection, cond, null, "pub_date desc");
	}

	@Override
	public void onLoadFinished(android.content.Loader<Cursor> arg0, Cursor cursor) {
		if (cursor != null) {
			// collect id of all items in order
			itemIdList.clear();
			try {
				while (cursor != null && cursor.moveToNext()) {
					itemIdList.add(cursor.getString(0));
				}
			} finally {
				cursor.close();
			}
			
			initPager();
		}
	}

	@Override
	public void onLoaderReset(android.content.Loader<Cursor> arg0) {
		pager.removeAllViews();
	}
}
